java使用invoke反射调用成员函数时遇到的坑 您所在的位置:网站首页 The arguments object java使用invoke反射调用成员函数时遇到的坑

java使用invoke反射调用成员函数时遇到的坑

2024-06-27 02:03| 来源: 网络整理| 查看: 265

参考博客:https://www.cnblogs.com/firstdream/p/4830960.html

问题背景:

使用invoke传递参数时,要考虑参数的个数:

public Object invoke(Object obj, Object... args) /* Parameters: obj - the object the underlying method is invoked from args - the arguments used for the method call Returns: the result of dispatching the method represented by this object on obj with parameters args */

以下两个成员函数,虽然一个是可变参数,一个是Object[]。但是在invoke函数中传参时当做一个Object来看待,如果想传递参数Object[] objects = {a, b};(见代码),需要加(Object)类型强制转换,

否则报错 java.lang.IllegalArgumentException: wrong number of arguments

public void addpp(Object... objects) public int addproxy(Object[] objects)

 以下的成员函数,参数个数为2个,两个int[],在invoke函数传参时可以传一个Object[2]不用加(Object)强制类型转换。

public int add(int[] a, int[] b)

 

代码概述:

有三个函数:

参数分别为可变参数、Object[]、两个int[],

主函数:

传递同样的两个数组,将两个数组转换为一个Object[],

使用invoke反射调用三种方法时,要对Object[]参数酌情加强制类型转换。

 

以下是测试代码:

package Ques; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class Father { public void addpp(Object... objects) { System.out.println(objects.length); //System.out.println("结果是 " + addproxy(objects)); } public int add(int[] a, int[] b) { return 0; } public int addproxy(Object[] objects) { return add((int[]) objects[0], (int[]) objects[1]); } public static void main(String[] args) { int[] a = {0, 1}; int[] b = {1, 2}; Object[] objects = {a, b}; Father son = new Father(); try { Method m = Father.class.getDeclaredMethod("addpp", Object[].class); Method m2 = Father.class.getDeclaredMethod("add", int[].class, int[].class); Method m3 = Father.class.getDeclaredMethod("addproxy", Object[].class); System.out.println("参数: m " + m.getParameterCount());//-->结果为1 System.out.println("参数: m2 " + m2.getParameterCount());//-->结果为2 System.out.println("参数: m3 " + m3.getParameterCount());//-->结果为1 m.invoke(son, (Object) objects);//输入的参数个数为1个 m2.invoke(son, objects);//输入的参数个数为2个 m3.invoke(son, (Object) objects);//输入的参数个数为1个 } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } /*son.addpp(a,b);//-->结果为2 son.addpp(objects);//-->结果为2 son.addpp(a);//-->结果为1 son.addpp(new Object[2]);//-->结果为2 son.addpp(new int[2]);//-->结果为1 son.addpp(new String[2]);//-->结果为2 son.addpp((Object)objects);//-->结果为1 son.addpp((Object) new String[2]);//-->结果为1*/ } }

 

 



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有